#include "connectpage.h"
#include "ui_connectpage.h"

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QUrl>
#include <QDebug>
#include <QtMqtt/QMqttClient>


connectPage::connectPage(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::connectPage)
{
    ui->setupUi(this);
}

connectPage::~connectPage()
{
    delete ui;
}

void connectPage::on_pushButton_confirm_clicked()
{
    QString username = this->ui->lineEdit_username->text();
    QString password = this->ui->lineEdit_password->text();

    if(username.isEmpty() || password.isEmpty())
    {
        qDebug () << "请输入用户名或密码" << __LINE__ << __FILE_NAME__;
        return;
    }

    QJsonObject json;
    json["username"] = username;
    json["password"] = password;

    QNetworkAccessManager* manager = new QNetworkAccessManager(this);

    QMqttClient* client = new QMqttClient();

    connect(client, &QMqttClient::connected, this, [](){
        qDebug() << "mqtt连接成功";

    });



    connect(manager, &QNetworkAccessManager::finished, this,[client](QNetworkReply *reply){
        QByteArray responseData = reply->readAll();

        QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
        qDebug() << jsonDoc;
        if(jsonDoc["code"] == 200)
        {
            QString clientId = jsonDoc["clientID"].toString();
            client->setClientId(clientId);
            client->setPort(1883);
            client->setUsername("sleep");
            client->setPassword("520520");
            client->setHostname("192.168.209.205");

            client->connectToHost();
        }
        else
        {
            qDebug() << "请求失败";
        }

    });

    QNetworkRequest request(QUrl("http://127.0.0.1:5000/IOT_DM/Mqtt/Connect"));

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");

    QJsonDocument doc(json);
    QByteArray data = doc.toJson(QJsonDocument::Compact);

    manager->post(request, data);



}

